<?php require_once('PhpSerial.php');echo 'receive';

$PhpSerial=new PhpSerial;
$PhpSerial->deviceSet('COM7');

// set code below will not be return OK - ERROR
/*$PhpSerial->confBaudRate(115200);
$PhpSerial->confParity("none");
$PhpSerial->confCharacterLength(8);
$PhpSerial->confStopBits(1);
$PhpSerial->confFlowControl("none");*/

if($PhpSerial->deviceOpen()){
	//stream_set_timeout($PhpSerial->_dHandle, 10)
    $PhpSerial->sendMessage("AT+CMGF=1\r");
    $out=$PhpSerial->readPort();
    if(strpos($out,"OK")!==false){
        $number_read = 20;
        for ($k = 1; $k <= $number_read; $k++) {
            $PhpSerial->sendMessage("AT+CMGR=$k\n",1);
            $inbox=$PhpSerial->readPort();
            if( strpos($inbox,'ERROR') === false ){
                $inbox=preg_replace(array("/\r|\nOK|\+CMTI: \"SM\",[0-9]+/"),"",$inbox);
                $arr=explode("+CMGR:",$inbox);
                if(count($arr)>=2){
                    $fields=preg_split('/\r|\n/',$arr[1],2);
                    $headArr=explode(',',$fields[0]);
                    if(count($headArr)>=3){
                        $sender=str_replace(array('+','"',','),'',$headArr[1]);
                        $date='20'.str_replace('"','',$headArr[3]);
                        $time=substr($headArr[4],0,8);
                        $msg=preg_replace('/[^(\x20-\x7F)]*/','',$fields[1]);
                        try{
                            $dbconn=pg_connect("host=localhost port=5432 dbname=sms user=postgres password=admin");
                            pg_query_params($dbconn,"select in_insert($1,$2,$3,$4,$5)",array($sender,'84905000705', trim($msg),$date,$time));
                            $PhpSerial->sendMessage("AT+CMGD=$k\r",1);
                        }
                        catch(Exception $e){
                            var_dump($e);
                        }
                    }
                }
            } else { break; }
        }
    }
}
$PhpSerial->deviceClose();
?>